package com.zhangye.test.aps;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.zhangye.test.model.Admin;
import com.zhangye.test.service.AliPayAsyncServices;
import com.zhangye.test.service.AliPayOrderInfoServices;
import com.zhangye.test.service.AliPayVerifyServices;
import com.zhangye.test.service.SafeSessionService;

/**
 * 
 * @author 支付宝支付入口
 *
 */
@Controller
@RequestMapping("api/aliPays")
public class AliPayApis {

	Logger logger = LoggerFactory.getLogger(AliPayApis.class);

	@Autowired
	private SafeSessionService safeSessionService;// 安全登录

	@Autowired
	private AliPayOrderInfoServices aliPayOrderInfoService;// 创建订单

	@Autowired
	private AliPayVerifyServices aliPayVerifyService;// 同步通知验证

	@Autowired
	private AliPayAsyncServices aliPayAsyncService;// 异步通知验证
	

	/**
	 * 创建签名后订单 
	 * 作者： 张叶
	 * 创建时间：2018年8月2日  下午5:47:24
	 */
	@ResponseBody
	@RequestMapping("/orderNew")
	public ApiResult orderNew(HttpServletRequest request, String datas) {
		ApiResult result = new ApiResult();
		String reqParam = request.getParameter("datas");
		Admin m = safeSessionService.getCurrent(request);
		if (m != null) {
			JSONObject jasonObject = JSONObject.fromObject(reqParam);
			Map<String, String> map = new HashMap<String, String>();
			try {
				map = aliPayOrderInfoService.orderNew(jasonObject,m.getId());
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			if (MapUtils.isNotEmpty(map)) {
				if (map.get("status").equals("0")) {
					result.data.put("orderInfo", map.get("orderInfo"));
					result.msg.desc = "成功";
					result.msg.status = 0;
				} else if (map.get("status").equals("2")) {
					result.msg.desc = "金额错误，请重试";
					result.msg.status = 3;
				}
			} else {
				result.msg.desc = "系统错误，请重试";
				result.msg.status = 1;
			}
		} else {
			result.msg.desc = "当前登录已失效，请重新登录 ";
			result.msg.status = 2;
		}
		logger.info("api/aliPay/order响应数据：" + JSON.toJSONString(result));
		return result;
	}

	/**
	 * 同步通知验证 
	 * 作者： 张叶
	 * 创建时间：2018年8月2日  下午5:47:30
	 */
	@ResponseBody
	@RequestMapping("/verifyNew")
	public ApiResult verifyNew(HttpServletRequest request, String datas) {

		ApiResult result = new ApiResult();
		String reqParam = request.getParameter("datas");

		JSONObject jasonObject = JSONObject.fromObject(reqParam);
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = aliPayVerifyService.verifyNew(jasonObject);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if (MapUtils.isNotEmpty(map)) {
			if (map.get("resultCode").equals("0")) {
				result.data.put("outTradeNo", map.get("outTradeNo"));
				result.msg.desc = "成功";
				result.msg.status = 0;
			} else {
				result.msg.desc = "验证失败";
				result.msg.status = 2;
			}
		} else {
			result.msg.desc = "系统错误，请重试";
			result.msg.status = 1;
		}
		logger.info("api/aliPay/verify响应数据：" + JSON.toJSONString(result));
		return result;
	}

	
	/**
	 * 支付宝异步通知
	 * 作者： 张叶
	 * 创建时间：2018年8月2日  下午5:47:38
	 */
	@ResponseBody
	@RequestMapping(value = "/async", produces = "application/json;charset=utf-8;")
	public String async(HttpServletRequest request) {

		Map<String, String> params = new HashMap<String, String>();
		Map<String, String> sign = new HashMap<String, String>();
		String result = "";
		try {
			request.setCharacterEncoding("utf-8");
			Map requestParams = request.getParameterMap();
			for (Iterator iter = requestParams.keySet().iterator(); iter
					.hasNext();) {
				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i]
							: valueStr + values[i] + ",";
				}
				System.out.println(">>>>>参数" + name + ":" + valueStr);
				if (name.equals("sign") || name.equals("sign_type")) {
					if (name.equals("sign")) {
						sign.put(name, valueStr);
					}
				} else {
					params.put(name, URLEncoder.encode(valueStr, "UTF-8"));
				}
			}

			result = aliPayAsyncService.async(params, sign);

		} catch (UnsupportedEncodingException | ParseException e) {
			e.printStackTrace();
		}

		return result;
	}
}
